/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gestionnaires;

import java.util.ArrayList;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import modeles.Produit;
import modeles.Tag;

/**
 *
 * @author Christian
 */
@Stateless
public class GestionnaireTags {

    @PersistenceContext
    private EntityManager em;
    
    public void creeTagsDeTest() {
        Tag tag = new Tag("FPS");
        em.persist(tag);
        tag = new Tag("Reflexion");
        em.persist(tag);
        tag = new Tag("Gestion");
        em.persist(tag);
        tag = new Tag("Simulation");
        em.persist(tag);
        tag = new Tag("Aventure");
        em.persist(tag);
        tag = new Tag("Action");
        em.persist(tag);
        tag = new Tag("Infiltration");
        em.persist(tag);
        tag = new Tag("Course");
        em.persist(tag);
        tag = new Tag("Jeu de role");
        em.persist(tag);
        tag = new Tag("Arcade");
        em.persist(tag);
    }
    
    public Tag creeTag(String NomTag) {
        if(NomTag == null)
            return null;
        if(NomTag.isEmpty())
            return null;
        if(getTagByName(NomTag) != null)
            return null;
        Tag tag = new Tag(NomTag);
        em.persist(tag);
        return tag;
    }
    
     public Collection<Tag> getAllTags() {
        Query q = em.createQuery("select o from Tag o", Tag.class);
        return q.getResultList();
    }

    public Tag getTagById(int id) {
        Query q = em.createQuery("select o from Tag o where o.id=" + id, Tag.class);
        if(q.getResultList().size() <= 0) return null;
        return (Tag) q.getResultList().get(0);
    }

    public Tag getTagByName(String tag) {
        Query q = em.createQuery("select o from Tag o where o.tag like '" + tag + "'", Tag.class);
        if(q.getResultList().size() <= 0) return null;
        return (Tag) q.getResultList().get(0);
    }

    public void suprimeTagByName(String tag) {
        Tag temp = getTagByName(tag);
        if(temp == null || tag.isEmpty())
            return;
        suprimeTagById(temp.getId());
    }

    public void suprimeTagById(int id) {
        Tag tag = getTagById(id);
        ArrayList<Produit> produits = new ArrayList<Produit>(tag.getProduits());
        for(Produit p : produits){
            p.removeTag(tag);
        }
        em.remove(tag);
    }
    
    public Collection<Produit> getAllProduitsByTag(int start, int offset, String tag) {
        if(start < 0 || offset <0)
            return null;
        Query q = em.createQuery("select o.produits from Tag o where o.tag like '" + tag + "'", Tag.class);
        q.setFirstResult(start);
        q.setMaxResults(offset);
        return q.getResultList();
    }
    
}
